package com.example.backend.repository;

import com.example.backend.domain.entity.SavedSearchCondition;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 保存搜索条件Repository
 */
@Repository
public interface SavedSearchConditionRepository extends JpaRepository<SavedSearchCondition, Long> {

    /**
     * 根据用户ID查找保存的搜索条件
     */
    Page<SavedSearchCondition> findByUserIdOrderByLastUsedAtDesc(Long userId, Pageable pageable);

    /**
     * 查找公开的搜索条件
     */
    Page<SavedSearchCondition> findByIsPublicTrueOrderByUsageCountDesc(Pageable pageable);

    /**
     * 根据用户ID和搜索名称查找
     */
    Optional<SavedSearchCondition> findByUserIdAndSearchName(Long userId, String searchName);

    /**
     * 查找用户的默认搜索条件
     */
    List<SavedSearchCondition> findByUserIdAndIsDefaultTrue(Long userId);

    /**
     * 统计用户的搜索条件数量
     */
    @Query("SELECT COUNT(s) FROM SavedSearchCondition s WHERE s.user.id = :userId")
    Long countByUserId(@Param("userId") Long userId);

    /**
     * 查找热门搜索条件
     */
    @Query("SELECT s FROM SavedSearchCondition s WHERE s.isPublic = true ORDER BY s.usageCount DESC")
    List<SavedSearchCondition> findPopularSearchConditions(Pageable pageable);

    /**
     * 查找最近使用的搜索条件
     */
    @Query("SELECT s FROM SavedSearchCondition s WHERE s.user.id = :userId ORDER BY s.lastUsedAt DESC")
    List<SavedSearchCondition> findRecentSearchConditions(@Param("userId") Long userId, Pageable pageable);

    /**
     * 更新使用次数
     */
    @Query("UPDATE SavedSearchCondition s SET s.usageCount = s.usageCount + 1, s.lastUsedAt = CURRENT_TIMESTAMP WHERE s.id = :id")
    void incrementUsageCount(@Param("id") Long id);

    /**
     * 删除用户的搜索条件
     */
    void deleteByUserIdAndId(Long userId, Long id);

    /**
     * 批量删除搜索条件
     */
    void deleteByUserIdAndIdIn(Long userId, List<Long> ids);
}
